//
//  ImageScrollView.m
//  Sydeny
//
//  Created by Rainbow on 8/8/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ImageScrollView.h"
#import "ITSGetImageForButtonOperation.h"
#import "ImageButton.h"
#import "UtilHelper.h"
#import "ImageInfo.h"
#import "ImageZoomableView.h"

@implementation ImageScrollView

-(id)initWithImages:(NSArray *)aImages
{
    self = [super init];
    if (self) {
        images = [aImages retain];
        operationQueue = [[NSOperationQueue alloc] init];
        self.pagingEnabled = YES;
        [self loadComponent];
    }
    return self;
}

-(void)loadComponent
{
    self.contentSize = CGSizeMake(150 * [images count], 90);
    for (int i = 0; i< [images count]; i++) {
        ImageInfo *imageInfo = [images objectAtIndex:i];
        ImageButton *imageButton = [[ImageButton alloc] initWithFrame:CGRectMake(15 + 150 * i, 0, 120, 90)];
        [imageButton setBackgroundImage:[UIImage imageNamed:@"240_180.png"] forState:UIControlStateNormal];
        UIImage *image = [UtilHelper getImageFromDocument:imageInfo.thumbImagUrl];
        if (image != nil) {
            [imageButton setBackgroundImage:image forState:UIControlStateNormal];
        }
        else
        {  
            ITSGetImageForButtonOperation *operation = [[ITSGetImageForButtonOperation alloc] initWithButton:imageButton imageUrl:[UtilHelper getFullImageUrl:imageInfo.thumbImagUrl] nameToSave:imageInfo.thumbImagUrl];
            [operationQueue addOperation:operation];
            [operation release];
        }
        [self addSubview:imageButton];
        imageButton.tag = i+10;
        [imageButton addTarget:self action:@selector(tapOnImage:) forControlEvents:UIControlEventTouchUpInside];
        [imageButton release];
    }
}

- (void)tapOnImage:(ImageButton *)button
{
    int tag = button.tag - 10;
    ImageInfo *imageInfo = [images objectAtIndex:tag];
    ImageZoomableView *imageZoomableView = [[[ImageZoomableView alloc] init] autorelease];
    CGRect frameInWindow = [self convertRect:button.frame toView:self.window];
    imageZoomableView.frame = frameInWindow;
    [imageZoomableView displayImage:imageInfo.imageUrl];
    [self.window addSubview:imageZoomableView];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5f];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    imageZoomableView.frame = [UIScreen mainScreen].bounds;
    [UIView commitAnimations];

}

- (void)dealloc
{
    [images release];
    [operationQueue release];
    [super dealloc];
}

@end
